package com.toycloud.business.controller.upload;

import cn.hutool.core.util.ObjectUtil;
import com.toycloud.business.service.ISysUploadTaskService;
import com.toycloud.common.core.controller.BaseController;
import com.toycloud.common.core.domain.R;
import com.toycloud.common.core.validate.AddGroup;


import com.toycloud.system.domain.SysUploadTask;
import com.toycloud.system.domain.bo.InitTaskParam;
import com.toycloud.system.domain.dto.TaskInfoDTO;
import com.toycloud.system.domain.vo.SysOssVo;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/multipart/minio/tasks")
public class MultipartUploadController extends BaseController {

    private final ISysUploadTaskService sysUploadTaskService;

    /**
     * 创建一个上传任务
     * @return
     */
    @PostMapping
    public R<TaskInfoDTO> initTask(@Validated(AddGroup.class) @RequestBody InitTaskParam param) {
        return R.ok(sysUploadTaskService.initTask(param));
    }

    /**
     * 获取每个分片的预签名上传地址
     * @param identifier
     * @param partNumber
     * @return
     */
    @GetMapping("/{identifier}/{partNumber}")
    public R<?> preSignUploadUrl(@PathVariable("identifier") String identifier, @PathVariable("partNumber") Integer partNumber) {
        SysUploadTask task = sysUploadTaskService.getByIdentifier(identifier);
        if (ObjectUtil.isNull(task)) {
            return R.fail("分片任务不存在!");
        }
        return R.ok("获取每个分片的预签名上传地址成功", sysUploadTaskService.genPreSignUploadUrl(task.getObjectKey(), task.getUploadId(), partNumber));
    }

    /**
     * 合并分片
     *
     * @param identifier
     * @return
     */
    @PostMapping("/merge/{identifier}")
    public R merge(@PathVariable("identifier") String identifier) {
        SysOssVo oss = sysUploadTaskService.merge(identifier);
        Map<String, String> map = new HashMap<>(2);
        map.put("url", oss.getUrl());
        map.put("fileName", oss.getOriginalName());
        map.put("ossId", oss.getOssId().toString());
        return R.ok( map,"文件合并成功");
    }
}
